package com.fagp.register.controller;

import com.zebra.common.HttpClient;
import com.zebra.common.concurrent.ZebraExecutorManager;
import com.zebra.register.RegisterConfigInfoManager;
import com.zebra.register.RegisterServerService;
import com.zebra.register.ServerRedisService;
import com.zebra.remoting.config.GatewayServerInfo;
import com.zebra.remoting.config.GwRegisterResponse;
import com.zebra.remoting.config.RegisterServerInfo;
import com.zebra.remoting.config.TmsServerInfo;
import com.zebra.remoting.tms.TmsToRegisterMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class RegisterServerController {


    @Autowired
    private RegisterServerService registerServerService;
    @Autowired
    private ServerRedisService serverRedisService;

    /**
     * GW，TMS 远程调用注册中心【根据配置，或者微服务调用某个】；
     * 1，发起TCP链接，链接成功则写入redis，
     * 2, 向其他注册中心服务发消息；/register/server/in
     * @param request
     * @return
     */
    @PostMapping(value = "/register/tms")
    @ResponseBody
    public TmsServerInfo registerServerAndRedis(@RequestBody TmsToRegisterMessage request){
        log.info("---Register TMS msg {}", request.toString());
        try {
            registerServerService.registerTmsAndRedis(request);
            TmsServerInfo serverInfo = request.getServerInfo();
            sendMsgTOther("/connect/tms/"+serverInfo.getServerId()+"/"+serverInfo.getInIP()+"/"+serverInfo.getPort());
            return request.getServerInfo();
        } catch (Exception e) {
            log.error("Register tms", e);
            return null;
        }

    }
    @PostMapping(value = "/register/gw")
    @ResponseBody
    public GwRegisterResponse registerGatewayAndRedis(@RequestBody GatewayServerInfo request){
        log.info("---Register Gateway msg {}", request.toString());
        try {
            GwRegisterResponse gwRegisterResponse = registerServerService.registerGwAndRedis(request);
            GatewayServerInfo serverInfo = gwRegisterResponse.getGwInfo();
            String ip = serverInfo.getInner() == 1 ? serverInfo.getInIP() : serverInfo.getOutIP();
            sendMsgTOther("/connect/gw/"+serverInfo.getServerId()+"/"+ip+"/"+ip+"/"+serverInfo.getPort());
            return gwRegisterResponse;
        } catch (Exception e) {
            log.error("Register Gateway", e);
            return null;
        }
    }

    // 2 向其他注册中心发消息 需要注册
    private void sendMsgTOther(String urlPostfix){
        List<RegisterServerInfo> set = serverRedisService.findRegisterALL();
        if (null == set || set.isEmpty() || set.size() == 1){
            return;
        }
        set.remove(RegisterConfigInfoManager.getInstance().getRegisterServerInfo());
        if (set.isEmpty()){
            return;
        }
        ZebraExecutorManager.getInstance().getDefaultExecutor().execute(() -> {
            set.stream().forEach(rsi -> {
                try {
                    String url = "http://"+rsi.getInIP()+":"+rsi.getPort()+urlPostfix;
                    log.info("Register to Register  url {}", url);
                    HttpClient.getByUrl(url);
                } catch (Exception e) {
                    log.error("Register to Register http failure ip {} port {} {}",  rsi.getInIP(), rsi.getPort());
                }

            });
        });

    }

    /**
     *  1，其他注册中心 发来的注册信息
     * @return
     */
    @GetMapping(value = "/connect/tms/{serverid}/{ip}/{port}")
    @ResponseBody
    public Integer connectTms(@PathVariable("serverid") int serverid, @PathVariable("ip") String ip, @PathVariable("port") int port){
        log.info("---Connect Tms  sid {} ip {} port {}", serverid, ip, port);
        try {
            TmsToRegisterMessage message = new TmsToRegisterMessage();
            TmsServerInfo tmsServerInfo = new TmsServerInfo();
            tmsServerInfo.setServerId(serverid);
            tmsServerInfo.setInIP(ip);
            tmsServerInfo.setPort(port);
            message.setServerInfo(tmsServerInfo);
            registerServerService.connectTms(message);
        } catch (Exception e) {
            log.error("Register", e);
            return 0;
        }
        return 1;
    }
    /**
     *  1，其他注册中心 发来的注册信息
     * @return
     */
    @GetMapping(value = "/connect/gw/{serverid}/{inip}/{outip}/{port}")
    @ResponseBody
    public Integer connectGw(@PathVariable("serverid") int serverid,
                             @PathVariable("inip") String inip,
                             @PathVariable("outip") String outIp,
                             @PathVariable("port") int port){
        log.info("---Connect Gateway  sid {} ip {} outIp {} port {}", serverid, inip, outIp, port);
        try {
            GatewayServerInfo gatewayServerInfo = new GatewayServerInfo();
            gatewayServerInfo.setServerId(serverid);
            gatewayServerInfo.setInIP(inip);
            gatewayServerInfo.setOutIP(outIp);
            gatewayServerInfo.setPort(port);
            registerServerService.connectGw(gatewayServerInfo);
            return 1;
        } catch (Exception e) {
            log.error("Register", e);
            return 0;
        }

    }



}
